<?php
/**
 * Created by PhpStorm.
 * User: yh
 * Date: 2018/12/19
 * Time: 下午3:21
 */

namespace app\admin\controller;

use think\Cache;
use think\Exception;
use think\Db;
use app\common\model\Ordershop as commonorder;
use app\common\model\Message;

class Ordershop extends Common
{
    //订单列表
    public function order_data($status)
    {
        $this->assign('status', $status);
        $where = [];
        if ($status == 'all') {
            $this->templateTitle('全部订单');
            $where['or.id'] = ['gt', 0];
        } elseif ($status == '0') {
            $this->templateTitle('未支付订单');
            $where['or.status'] = 0;
        } elseif ($status == 1) {
            $this->templateTitle('待发货订单');
            $where['or.status'] = 1;
        } elseif ($status == 2) {
            $this->templateTitle('待收货订单');
            $where['or.status'] = 2;
        } elseif ($status == 3) {
            $this->templateTitle('已完成订单');
            $where['or.status'] = 3;
        } elseif ($status == -1) {
            $this->templateTitle('取消订单');
            $where['or.status'] = -1;
        }


        //搜索条件-用户
        $user_condition = request()->param("user_condition");
        $this->assign("user_condition", $user_condition);
        if ($user_condition) {
            $where["us.username|us.selfphone|us.id"] = $user_condition;
        }
        //搜索条件-订单
        $or_condition = request()->param("or_condition");
        $this->assign("or_condition", $or_condition);
        if ($or_condition) {
            $where["or.id|or.order_sn"] = $or_condition;
        }

        //搜索条件-注册时间
        if (request()->has("time_range")) {
            //解析时间
            $timeRange = request()->param("time_range");
            $timeRange = explode(" ~ ", $timeRange);
            //模板渲染值
            $this->assign("range_start", ["time_range" => $timeRange[0]]);
            $this->assign("range_end", ["time_range" => $timeRange[1]]);

            $where['or.create_time'] = ["BETWEEN", [strtotime($timeRange[0] . " 00:00:00"), strtotime($timeRange[1] . " 23:59:59")]];

        } else {
            //模板渲染值
            $this->assign("range_start", ["time_range" => '2018-01-01']);
            $this->assign("range_end", ["time_range" => date("Y-m-d")]);
        }

        $list = Db::name("sell_order")
            ->alias('or')
            ->join('__USER__ us', 'us.id=or.uid', 'LEFT')
            ->where($where)
            ->order("or.id DESC")
            ->field('or.*,us.username as nick_name,us.selfphone as mobile')
            ->paginate(10);


        $this->assign("list", $list);
        $all = Db::name("sell_order")
            ->alias('or')
            ->join('__USER__ us', 'us.id=or.uid', 'LEFT')
            ->where($where)
            ->field('sum(or.total_price) as all_price,sum(or.money) as all_money,sum(or.coin) as all_coin')
            ->find();
        $this->assign("all", $all);
        return $this->fetch('ordershop/index');
    }

    /*全部订单*/
    public function statusAll()
    {
        return $this->order_data('all');
    }

    /*未支付订单*/
    public function status0()
    {
        return $this->order_data('0');
    }

    /*待发货订单*/
    public function status1()
    {
        return $this->order_data('1');
    }

    /*待收货订单*/
    public function status2()
    {
        return $this->order_data('2');
    }

    /*已完成订单*/
    public function status3()
    {
        return $this->order_data('3');
    }

    /*已取消订单*/
    public function status_1()
    {
        return $this->order_data('-1');
    }

    /*订单详情*/
    public function order_info()
    {
        try {
            $orderid = input('id');
            $this->layoutModal();
            $info = commonorder::orderInfo('', $orderid, '', 2);
//            if ($info['up1_id'] > 0) {
//                $up1 = Db::name('user')
//                    ->where('id', $info['up1_id'])
//                    ->find();
//                $up1 = 'ID：' . $up1['id'] . ' / 手机：' . $up1['mobile'] . ' / 昵称：' . $up1['nick_name'];
//            } else {
//                $up1 = '';
//            }
//            if ($info['up2_id'] > 0) {
//                $up2 = Db::name('user')
//                    ->where('id', $info['up2_id'])
//                    ->find();
//                $up2 = 'ID：' . $up2['id'] . ' / 手机：' . $up2['mobile'] . ' / 昵称：' . $up2['nick_name'];
//            } else {
//                $up2 = '';
//            }
//            $this->assign('up1', $up1);
//            $this->assign('up2', $up2);
            $uinfo = Db::name('user')->where('id', $info['uid'])->find();
            $this->assign('uinfo', $uinfo);
            $this->assign('info', $info);
            return $this->fetch();
        } catch (\Exception $exception) {
            global $admin_has_exception;
            $admin_has_exception = true;
            echo $exception->getMessage();
            exit;
        }
    }

    /*删除订单*/
    public function remove()
    {
        $orderid = input('id');
        if (empty($orderid)) {
            $this->ajaxError("参数错误！");
        }
        $order = Db::name('sell_order')
            ->where('id', $orderid)
            ->find();
        if (!$order || $order['status'] != -1) {
            $this->ajaxError('无此订单或订单未取消禁止删除');
        }
        /*删除订单*/
        Db::name('sell_order')
            ->where('id', $orderid)
            ->delete();
        /*删除订单商品*/
        Db::name('sell_order_goods')
            ->where('orderid', $orderid)
            ->delete();
        Message::admin_log(0, '删除-订单-' . $orderid);
        $this->ajaxSuccess("删除成功！");
    }

    /*确认收货*/
    public function confirm_receive()
    {
        if (request()->isAjax()) {
            $order_id = input('id');
            $uid = input('uid');
            try {
                $res = commonorder::orderReceive($uid, $order_id);
                Message::admin_log(0, '确认收货-订单-' . $order_id);
                $this->ajaxSuccess($res);
            } catch (\Exception $exception) {
                global $admin_has_exception;
                $admin_has_exception = true;
                $this->ajaxError($exception->getMessage());
            }
        }
    }


    public function send()
    {
        $order_id = input('id');
        $order = Db::name('sell_order')
            ->alias('o')
            ->join('__USER__ u', 'u.id=o.uid', 'LEFT')
            ->where('o.id', $order_id)
            ->field('o.*,u.username nick_name,u.selfphone as umobile')
            ->find();
        if (request()->isGet()) {
            $this->layoutModal();
            $this->assign('info', $order);
            $this->assign("range_start2", ["send_time" => date("Y-m-d H:i")]);
            return $this->fetch();
        }
        if (request()->isAjax()) {
            try {
                if ($order['status'] != 1) {
                    $this->ajaxError('非待发货订单');
                }

                $send_company = trim(input('send_company'));
                if (empty($send_company)) {
                    $this->ajaxError('请输入快递公司名称');
                }
                $send_sn = trim(input('send_sn'));
                if (empty($send_sn)) {
                    $this->ajaxError('请输入快递单号');
                }
                $send_time = trim(input('send_time'));
                $data = [
                    'status' => 2,
                    'send_company' => $send_company,
                    'send_sn' => $send_sn,
                    'send_time' => empty($send_time) ? now_datetime() : strtotime($send_time)
                ];
                $save = Db::name('sell_order')->where('id', $order_id)->update($data);
                if ($save) {
                    Message::admin_log(0, '确认发货-订单-' . $order_id . '成功');
                    $this->ajaxSuccess('确认发货成功');
                } else {
                    Message::admin_log(0, '确认发货-订单-' . $order_id . '失败');
                    $this->ajaxSuccess('确认发货失败');
                }

            } catch (\Exception $exception) {
                global $admin_has_exception;
                $admin_has_exception = true;
                $this->ajaxError($exception->getMessage());
            }
        }
    }

    public function order_tip()
    {
        if (request()->isAjax()) {
            $time = Cache::store('redis')->get('admin_order_tip_time');
            $time = empty($time) ? 0 : $time;
            $list = Db('sell_order')
                ->where('status', 'gt', '0')
                ->where('pay_time', 'egt', $time)
                ->order('pay_time DESC')
                ->field('pay_time,order_sn,total_price')
                ->select();
            $html = '';
            foreach ($list as $item) {
                $html .= '<p>' . friend_date($item['pay_time']) . '<font>' . $item['order_sn'] . '</font><span>￥' . $item['total_price'] . '</span></p>';
            }
            Cache::store('redis')->set('admin_order_tip_time', now_datetime());
            $this->ajaxSuccess('成功', $html);
        }
    }


}